package com.adolph.netty.nettydemo;

import com.adolph.netty.dto.MessageObj;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

/**
 * 〈功能概述〉<br>
 *
 * @author: wangxiangjun
 * @date: 2020-10-09 9:51
 */

public class NettyClientHandler extends ChannelInboundHandlerAdapter {

    //当通道就绪时触发
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("服务端地址====="+ctx.channel().remoteAddress());
        MessageObj messageObj = new MessageObj();
        messageObj.setFromName("客户端");
        messageObj.setToName("服务器");
        messageObj.setMessage("你好！");
        ctx.writeAndFlush(messageObj);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("===========服务端断开连接");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("channelRead===========");
        ByteBuf byteBuf = (ByteBuf) msg;
        System.out.println("客户端接收服务端信息====="+byteBuf.toString(CharsetUtil.UTF_8));
//        System.out.println("服务端地址====="+ctx.channel().remoteAddress());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
